package com.cfh.web.json;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.SessionAware;

import com.cfh.domain.User;
import com.cfh.service.UserService;
import com.cfh.util.Tools;
import com.opensymphony.xwork2.ActionSupport;

public class UserLoginJson extends ActionSupport implements SessionAware {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(UserLoginJson.class);

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private UserService userService;
	private Map session;
	private String user;
	private String pass;
	private Map root;

	public void setSession(Map map) {
		session = map;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public void setPass(String pass) {
		this.pass = pass;
	}

	public String execute() {
		root = new HashMap();
		try {
			if (Tools.hasText(user) && Tools.hasText(pass)) {

				User currentUser = userService.getUserByUsernameAndPassword(user,
						pass);
				if (currentUser != null) {
					session.put("currentUser", currentUser);

					getRoot().put("success", new Boolean(true));
					if (logger.isDebugEnabled()) {
						logger.debug("execute() - login success - user=" + user); //$NON-NLS-1$
					}
					return SUCCESS;
				}
			}

			if (logger.isDebugEnabled()) {
				logger.debug("execute() - login false - user=" + user); //$NON-NLS-1$
			}
			getRoot().put("success", new Boolean(false));
			ArrayList errors = new ArrayList(1);
			Map error1 = new HashMap();
			error1.put("id", "pass");
			error1.put("msg", "用户名或密码错误");
			errors.add(error1);
			getRoot().put("errors", errors);

			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("login error:", e);
			throw new RuntimeException(e);
		}
		
	}

	public Map getRoot() {
		return root;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public UserService getUserService() {
		return userService;
	}

}
